package cn.doctorpda.conference.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.widget.Toast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.Timer;
import java.util.TimerTask;

import cn.doctorpda.conference.R;
import cn.doctorpda.conference.config.AppConfig;
import cn.doctorpda.conference.event.GetBitmap;
import cn.doctorpda.conference.event.UpdateMsg;
import cn.doctorpda.conference.ui.personal.dialog.PersonalSettingDialogFragment;
import cn.doctorpda.conference.ui.personal.dialog.SystemSettingDialogFragment;
import cn.doctorpda.conference.utils.L;
import cn.doctorpda.conference.utils.PictureUtils;
import cn.doctorpda.conference.utils.StringUtils;
import cn.doctorpda.conference.utils.T;
import cn.sharesdk.framework.ShareSDK;

public class MainActivity extends BaseActivity {

    public static final String KEY_MESSAGE = "message";
    public static final String KEY_EXTRAS = "extras";
    public static final String MESSAGE_RECEIVED_ACTION = "com.doctorpda.meeting.MESSAGE_RECEIVED_ACTION";
    public static boolean isForeground = false;
    private MessageReceiver mMessageReceiver;

    @Override
    protected Fragment createFragment() {
        return MainFragment.newInstance();
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_base;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 初始化ShareSDK
        ShareSDK.initSDK(this);
        // 极光推送的自定义消息
        registerMessageReceiver();
        // 注册eventbus
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onResume() {
        isForeground = true;
        super.onResume();
    }

    @Override
    protected void onPause() {
        isForeground = false;
        super.onPause();
    }

    public void registerMessageReceiver() {
        mMessageReceiver = new MessageReceiver();
        IntentFilter filter = new IntentFilter();
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(MESSAGE_RECEIVED_ACTION);
        registerReceiver(mMessageReceiver, filter);
    }

    public class MessageReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
                String messge = intent.getStringExtra(KEY_MESSAGE);
                String extras = intent.getStringExtra(KEY_EXTRAS);
                StringBuilder showMsg = new StringBuilder();
                showMsg.append(KEY_MESSAGE + " : " + messge + "\n");
                if (!StringUtils.isEmpty(extras)) {
                    showMsg.append(KEY_EXTRAS + " : " + extras + "\n");
                }
                T.showShort(MainActivity.this, showMsg.toString());
            }
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {

            if (requestCode == AppConfig.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
                Bitmap bmp;

                bmp = PictureUtils.reducePicSize(PictureUtils.decodeUriAsBitmap(Uri.parse(PersonalSettingDialogFragment.picFileFullName)), 180, 180);
                File file = new File(PersonalSettingDialogFragment.picFileFullName);
                EventBus.getDefault().post(new GetBitmap(bmp, file));

            } else if (requestCode == AppConfig.ALBUM_IMAGE_ACTIVITY_REQUEST_CODE) {

                Bitmap bmp_album;

                bmp_album = PictureUtils.reducePicSize(
                        PictureUtils.decodeUriAsBitmap(Uri.parse(selectImage(MainActivity.this, data))), 180, 180);
                File file = new File(selectImage(MainActivity.this, data));
                EventBus.getDefault().post(new GetBitmap(bmp_album, file));
            }


        }


    }

    public static String selectImage(Context context, Intent data) {
        Uri selectedImage = data.getData();
        // Log.e(TAG, selectedImage.toString());
        if (selectedImage != null) {
            String uriStr = selectedImage.toString();
            String path = uriStr.substring(10, uriStr.length());
            if (path.startsWith("com.sec.android.gallery3d")) {
                L.e("图库", "It's auto backup pic path:" + selectedImage.toString());
                return null;
            }
        }
        String[] filePathColumn = {MediaStore.Images.Media.DATA};
        Cursor cursor = context.getContentResolver().query(selectedImage, filePathColumn, null, null, null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();
        return picturePath;
    }


    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        unregisterReceiver(mMessageReceiver);
        super.onDestroy();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onInstall(UpdateMsg uri) {
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/ConferenceDown", "conference.apk");
        if (file == null) {
            file.mkdirs();
        }
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exitBy2Click();

        }
        return false;
    }

    /**
     * 双击
     */
    private static Boolean isExit = false;

    private void exitBy2Click() {
        Timer tExit = null;
        if (isExit == false) {
            isExit = true;
            T.showShort(this, "再按一次退出");
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false; // 取消
                }
            }, 2000); // 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务

        } else {
            onDestroy();
            finish();
            System.exit(0);//完全退出。。。造成前面的吐司不显示
        }
    }


}
